<?php

namespace App\Http\Controllers\Api;

use App\Models\ClockInDayRecord;
use App\Models\ClockInDayRule;
use App\Models\IntegralRule;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

/**
 * 签到控制器
 * Class ClockInController
 * @package App\Http\Controllers\Api
 */
class ClockInController extends Controller
{
    private $userId;
    public function __construct()
    {
//        $this->userId = 1;
        $this->userId = auth()->id();
    }

    /**
     * 获取签到弹框数据
     * @param Request $request
     * @return false|string
     */
    public function getAlertDayInfo(Request $request)
    {
        if (!$this->userId) {
            return jsonError('未登录', 4002, 402);
        }

        $today = date('Y-m-d'); // 当前日期
        $first = 1; // 表示每周星期一为开始日期 0表示每周日为开始日期
        $week = date('w', strtotime($today)); // 获取当前周的第几天 周日是 0 周一到周六是 1 - 6
        $week_start = date('Y-m-d',strtotime("$today -".($week ? $week - $first : 6).' days')); //获取本周开始日期，如果$week是0，则表示周日，减去 6 天
        $week_day = [];
        $week_day[] = $week_start;
        for ($i = 1; $i < 7; $i++) {
            $week_day[] = date('Y-m-d',strtotime("$week_start +$i days"));
        }
        $show_week_sign_day = false;
        $week_day_data = [];
        $week_sign_day = 0; // 本周已签到天数
        $check_today_sign = ClockInDayRecord::where(['user_id' => $this->userId, 'day_time' => $today, 'type' => 1])->first(); // 今日是否签到
        $reward_rule = ClockInDayRule::where('type', 2)->first(); // 奖励积分规则
        foreach ($week_day as $week_day_key => $week_day_val) {
            $item = [];
            $item['reward_day'] = false; // 是否为累计奖励日期
            $item['week_day'] = $week_day_val;
            $item['reward_integral'] = 0; // 奖励积分数
            $item['intro'] = strtotime($week_day_val.' 23:59:59') > time() ? '签到领取' : '已错过'; // 签到说明
            $item['clock_in_state'] = false; // 当日签到状态

            $check_sign = ClockInDayRecord::where(['user_id' => $this->userId, 'day_time' => $week_day_val, 'type' => 1])->first();
            if ($check_sign) {
                $item['clock_in_state'] = true;
                $item['intro'] = '已签到+'.$check_sign->integral;
            }
            if ($check_sign) $week_sign_day++; // 本周签到天数+1

            $clock_in_day_rule = ClockInDayRule::where('sort', $week_day_key + 1)->where('type', 1)->first();
            if ($clock_in_day_rule) {
                $item['integral'] = $clock_in_day_rule->integral; // 当日积分奖励数量
                $item['title'] = $clock_in_day_rule->title; // 当日签到标题
            }

            // 判断是否为累计奖励日期
            if ($reward_rule) {
                if ($week_day_key >= 4) {
                    if ($week_sign_day == 5 && !$show_week_sign_day) {
                        $item['reward_day'] = true;
                        $item['reward_integral'] = $reward_rule->integral;
                        $reward_sign_record = ClockInDayRecord::where(['user_id' => $this->userId, 'day_time' => $week_day_val])->sum('integral');
                        $item['intro'] = '已签到+'.$reward_sign_record;
                        $show_week_sign_day = true;
                    } else {
                        if (!$show_week_sign_day && $today < $week_day_val) {
                            $surplus_days = diff_between_two_days($today, $week_day_val); // 今天到循环日期的剩余天数
                            if (!$check_today_sign) $surplus_days++;
                            if ($week_sign_day + $surplus_days == $reward_rule->day) {
                                $item['reward_day'] = true;
                                $item['reward_integral'] = $reward_rule->integral;
                                $item['intro'] = '累计签到'.$reward_rule->day.'天额外+'.$reward_rule->integral;
                                $show_week_sign_day = true;
                            }
                        }
                    }
                }
            }

            array_push($week_day_data, $item);
        }

        $res_data = [
            'week_day_data' => $week_day_data,
            'today' => $week_day_data[$week ? $week - 1 : 7]['title'],
            'today_clock_in_state' => ClockInDayRecord::where(['user_id' => $this->userId, 'day_time' => date('Y-m-d')])->first() ? true : false
        ];

        return jsonSuccess($res_data);
    }

    /**
     * 签到页面，签到日历信息
     * @param Request $request
     * @return false|string
     */
    public function signCalendar(Request $request)
    {
        $month_time = $request->input('month_time'); // 2022-02

        if (empty($month_time)) {
            $month_time = date('Y-m');
        }
        $res['month_time'] = date('Y年m月', strtotime($month_time));
        $res['sign_all_integral'] = ClockInDayRecord::where('user_id', $this->userId)->sum('integral');

        $start_time = date('Y-m-1', strtotime($month_time)); // 该月份第一天
        $end_time = date('Y-m-d', strtotime("$start_time +1 month")); // 该月份最后一天
        $count_day = date('d', strtotime("$month_time +1 month -1 day")); // 该月份总天数

        // 获得本月的签到记录
        $clock_in_info = ClockInDayRecord::get_recode_day($start_time, $end_time, $this->userId);
        if ($clock_in_info) {
            $clock_in_info = array_column($clock_in_info, 'day_time');
        }

        $calendar = []; // 日历
        $start_day_week = date('w', strtotime($start_time));
        for ($i = 1; $i <= 42; $i++) {
            if ($i <= $start_day_week || $i > ($start_day_week + $count_day)) {
                // 去除日历开头结尾空日期
                $time_tmp = [
                    'day_num' => '',
                    'sign_state' => false,
                ];
            } else {
                $day = $i - $start_day_week;
                $time_tmp = [
                    'day_num' => $day,
                    'sign_state' => in_array(date('Y-m-'.sprintf("%02d", $day), strtotime($month_time)), $clock_in_info) ? true : false,
                ];
            }
            array_push($calendar, $time_tmp);
            continue;
        }

        $res['calendar'] = $calendar;
        $res['today_clock_in_state'] = ClockInDayRecord::where(['user_id' => $this->userId, 'day_time' => date('Y-m-d')])->first() ? true : false;
        return jsonSuccess($res);
    }

    /**
     * 每日签到
     * @param Request $request
     * @return false|string
     */
    public function clock_in(Request $request)
    {
        $month_time = date('Y-m-d');

        // 校验用户是否签到
        $check_sign = ClockInDayRecord::where(['user_id' => $this->userId, 'day_time' => $month_time])->first();
        if ($check_sign) {
            return jsonError('今日已经签到啦～');
        }

        $first = 1; // 表示每周星期一为开始日期 0表示每周日为开始日期
        $week = date('w', strtotime($month_time)); // 获取当前周的第几天 周日是 0 周一到周六是 1 - 6
        $week_start = date('Y-m-d',strtotime("$month_time -".($week ? $week - $first : 6).' days')); //获取本周开始日期，如果$week是0，则表示周日，减去 6 天
        $week_end = date('Y-m-d',strtotime("$month_time +".($week ? 7 - $week : 0).' days')); //获取本周开始日期

        // 本周内签到记录
        $clock_in_info = ClockInDayRecord::get_recode_day($week_start, $week_end, $this->userId);
        if ($clock_in_info) {
            $clock_in_info = array_column($clock_in_info, 'day_time');
        }

        $daily_rule = ClockInDayRule::where(['type' => 1, 'sort' => ($week ? $week : 7)])->first(); // 日常规则
        $reward_rule = ClockInDayRule::where('type', 2)->first(); // 奖励规则

        // 签到奖励
        $sign_act = IntegralRule::clockIn(12, $daily_rule->id, $this->userId, $month_time, $daily_rule->integral);
        if ($sign_act == false) {
            return jsonError('签到失败，请稍后再试～');
        }
        // 累计签到奖励
        if (count($clock_in_info) == 4) {
            $reward_act = IntegralRule::clockIn(13, $reward_rule->id, $this->userId, $month_time, $reward_rule->integral);
            if ($reward_act == false) {
                return jsonError('奖励发放失败，请前往个人中心提交"诉求建议"。');
            }
        }

        return jsonSuccess([], '签到成功！');
    }
}
